<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="m-table">
      <template #form="{ form }">
        <XForm style="padding: 16px 8px 8px" :fieldList="fieldList" :options="formOption" :formData="form"> </XForm>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="openAddRefund"> 添加退款 </el-button>
        <el-button type="primary" @click="batchOptionsEvent('audit')"> 批量审核 </el-button>
      </template>
      <template #GoodsSlot="{ row }">
        <ExpandList :show-expand="row?.RefundOrderList?.length > 1" :expand="row.expandStatus" @change="rendererView" :length="row?.RefundOrderList?.length">
          <template #default="{ expand }">
            <div class="product-item" v-for="(item, index) in getRows(row, expand)" :key="`${item.sku}${index}`">
              <div class="border-[var(--base-border-color)] border-[1px] rounded-[4px] p-[7px] text-[14px] relative leading-[20px] w-[338px]">
                <div class="flex">
                  <div class="inline-block"><VText title="系统SKU" :value="item.SKU" type="link" @click="onSku(item)" /></div>
                  <div class="text-red ml-[8px]">x{{ item.RefundNum }}</div>
                </div>
                <VText title="自定义SKU" :value="item.ClientSKU" />
                <VText title="渠道SKU" :value="item.SellerSKU" />
                <VText :value="item.ProductNameCn" />
                <VText title="ASIN" :value="item.ASIN" />
              </div>
            </div>
          </template>
        </ExpandList>
      </template>
    </VTable>
  </VPage>

  <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />

  <!-- <AddRefund ref="addRefundRef" v-model="addVisible" @refresh="handleRefresh" :id="refundId" @close="handleClose" /> -->
  <AddRefund ref="addRefundRef" v-model="addVisible" @refresh="handleRefresh" :id="refundId" @close="handleClose" />
</template>

<script setup lang="jsx">
import { refundList, auditRefund } from "./api"
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"

import ExpandList from "@/components/ExpandList/index.vue"

import { formOption, fieldList, tablecColumns, handleFunctions } from "./config.jsx"
import AddRefund from "./components/AddRefund/index.vue"



const addRefundRef = ref()
const openAddRefund = () => {
  // const select = tableRef?.value.$table.getCheckboxRecords()
  // if (select.length != 1) {
  //   ElMessage({ showClose: true, message: "只能选择一条数据！", type: "warning" })
  //   return false
  // }
  // console.log(addRefundRef.value)

  // addRefundRef.value.open()
  addVisible.value = true
}
const handleClose = () => {
  //
}
const handleChandleRefreshlose = () => {
  //
}
const addVisible = ref(false)

const approvalVisible = ref(false)
const rows = ref([])
// 批量审核
const handleBatchApproval = () => {
  const select = tableRef?.value.$table.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  rows.value = select
  approvalVisible.value = true
}

// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInputNew/index.vue"
const batchVisible = ref(false) //  表单编辑 弹窗状态
const currentConfirm = ref({}) // 表单编辑 配置
// 保存 弹窗 表单编辑
const handleConfirmSubmit = (param) => {
  console.log(currentConfirm.value)
  let api = null

  switch (currentConfirm.value.type) {
    case "audit": // 新增
      api = auditRefund
      break
  }
  api(param)
    .then((res) => {
      console.log(res)
      ElMessage.success("提交成功！")
      query()
    })
    .finally(() => {
      currentConfirm.value = {}
      batchVisible.value = false
    })
}

// 弹窗 表单编辑 打开
const batchOptionsEvent = async (e, params = {}) => {
  console.log(e)
  const select = tableRef?.value.$table.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  let confirm = {}
  switch (e) {
    case "audit": // 批量修改运输类型
      confirm = {
        ...batchOConfig.audit,
        type: e,
        length: select.length,
      }
      confirm.form = {
        Id: select.map((v) => v.id),
        IsApiRefund: 0,
      }
      break
    default:
      break
  }
  currentConfirm.value = confirm
  batchVisible.value = true
}

const batchOConfig = {
  audit: {
    title: "退款单申请",
    length: 0,
    fieldOptions: [
      {
        field: "AudiState",
        type: "select",
        label: "审核操作",
        options: {
          data: [
            { label: "审核中", value: "0" },
            { label: "审核通过", value: "1" },
            { label: "已退款", value: "2" },
            { label: "取消该申请", value: "3" },
          ],
        },
      },
      {
        field: "AuditRemark",
        label: "备注信息",
        type: "textarea",
        autosize: { minRows: 2, maxRows: 6 },
      },
      // {
      //   field: "is_api_refund",
      //   label: "是否api退款",
      //   type: "select",
      //   options: {
      //     data: [
      //       { label: "是", value: 1 },
      //       { label: "否", value: 0 },
      //     ],
      //   },
      // },
    ],
  },
}

// gotoDtl
const router = useRouter()
onActivated(() => {})
const handleFunction = ref({
  gotoDtl: (row) => {
    // AddressRef.value.open(row)
    router.push({
      path: "/user/irobotbox",
      state: {
        type: "ClientOrderCode",
        value: row.ClientOrderCode,
      },
    })
  },
})
onMounted(async () => {
  nextTick(() => {
    handleFunctions.value = handleFunction.value
  })
})

import action from "@/utils/action.js"
import ProductApi from "@/components/SelectProduct/api"
const onSku = (item) => {
  ProductApi.query({ sku: [item.SKU] }).then((res) => {
    if (res.data.length) {
      action.setGlobalState({
        changeMicoTabsPath: {
          path: "/goods/task/product/edit",
          type: "push",
          query: {
            type: "view",
            spuId: res.data?.[0]?.spu_id,
            sku: item.custom_sku,
          },
        },
      })
    }
  })
}

const tableRef = ref()
// 渲染表格列
const rendererView = (e) => {}
const getRows = (rows, expand) => {
  rows.expandStatus = expand
  const { RefundOrderList = [] } = rows || {}
  if (expand) return RefundOrderList
  if (!RefundOrderList?.length) return []
  if (RefundOrderList.length > 0 && RefundOrderList.length < 1) {
    return RefundOrderList
  }
  if (!expand) {
    return RefundOrderList?.slice(0, 1)
  }
}

const tableOptions = reactive({
  formConfig: {
    // save: "/oms/user/refund", // 必填，唯一
    data: {},
  },
  columns: [],
  scrollY: { enabled: false },
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: async ({ page, form }) => {
        let param = { ...page, ...form }
        let res = await refundList(getForm(param))
        return res
      },
    },
  },
})

// { fixed: "left", type: "checkbox", width: 50 },
tableOptions.columns = [{ fixed: "left", type: "checkbox", width: 50 }, ...tablecColumns.value]
const getForm = (params) => {
  let keys = ["ClientOrderCode"]
  keys.forEach((key) => {
    params[key] = params[key]?.split("\n")?.filter((v) => !!v.trim())
    params[key] = params[key]?.map((v) => v.trim())
  })

  return params
}
</script>
<style lang="scss" scoped></style>
